package com.dms.modules.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dms.common.exception.BusinessException;
import com.dms.modules.user.entity.UserAddress;
import com.dms.modules.user.dto.AddressDTO;
import com.dms.modules.user.mapper.UserAddressMapper;
import com.dms.modules.user.service.UserAddressService;
import com.dms.modules.user.vo.AddressVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户收货地址服务实现类
 */
@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressMapper, UserAddress> implements UserAddressService {

    @Override
    public List<AddressVO> getAddressList(Long userId) {
        List<UserAddress> addresses = lambdaQuery()
                .eq(UserAddress::getUserId, userId)
                .orderByDesc(UserAddress::getIsDefault)
                .orderByDesc(UserAddress::getCreateTime)
                .list();
        
        return addresses.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public AddressVO getAddressDetail(Long userId, Long addressId) {
        UserAddress address = getAddress(userId, addressId);
        return convertToVO(address);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addAddress(Long userId, AddressDTO addressDTO) {
        // 如果设置为默认地址，先将其他地址设为非默认
        if (addressDTO.getIsDefault() == 1) {
            baseMapper.updateDefaultStatus(userId, false);
        }
        
        UserAddress address = new UserAddress();
        BeanUtils.copyProperties(addressDTO, address);
        address.setUserId(userId);
        
        save(address);
        return address.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAddress(Long userId, Long addressId, AddressDTO addressDTO) {
        UserAddress address = getAddress(userId, addressId);
        
        // 如果设置为默认地址，先将其他地址设为非默认
        if (addressDTO.getIsDefault() == 1 && address.getIsDefault() != 1) {
            baseMapper.updateDefaultStatus(userId, false);
        }
        
        BeanUtils.copyProperties(addressDTO, address);
        address.setId(addressId);
        updateById(address);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAddress(Long userId, Long addressId) {
        UserAddress address = getAddress(userId, addressId);
        removeById(addressId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setDefaultAddress(Long userId, Long addressId) {
        UserAddress address = getAddress(userId, addressId);
        
        // 先将所有地址设为非默认
        baseMapper.updateDefaultStatus(userId, false);
        
        // 设置当前地址为默认
        address.setIsDefault(1);
        updateById(address);
    }

    @Override
    public AddressVO getDefaultAddress(Long userId) {
        UserAddress address = lambdaQuery()
                .eq(UserAddress::getUserId, userId)
                .eq(UserAddress::getIsDefault, 1)
                .one();
        
        return address != null ? convertToVO(address) : null;
    }

    /**
     * 获取用户地址
     */
    private UserAddress getAddress(Long userId, Long addressId) {
        UserAddress address = getById(addressId);
        if (address == null || !address.getUserId().equals(userId)) {
            throw new BusinessException("地址不存在");
        }
        return address;
    }

    /**
     * 转换为VO对象
     */
    private AddressVO convertToVO(UserAddress address) {
        if (address == null) {
            return null;
        }
        AddressVO vo = new AddressVO();
        BeanUtils.copyProperties(address, vo);
        return vo;
    }

    /**
     * 取消用户的其他默认地址
     */
    private void updateDefault(Long userId) {
        LambdaUpdateWrapper<UserAddress> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(UserAddress::getUserId, userId)
               .eq(UserAddress::getIsDefault, 1)
               .set(UserAddress::getIsDefault, 0);
        update(wrapper);
    }

    @Override
    public UserAddress getAddressById(Long id) {
        UserAddress address = getById(id);
        if (address == null) {
            throw new BusinessException("地址不存在");
        }
        return address;
    }
} 